<template>
  <FIModel v-model="visible" title="成员设置" @close="closeClick" @confirm="saveFunc">
    <el-row :gutter="20">
      <el-col :span="8">
        <FIFormItem prop="groupEname" label="岗位编码">
          <span>{{ editData.postEname }}</span>
        </FIFormItem>
      </el-col>
      <el-col :span="8">
        <FIFormItem prop="groupCname" label="岗位名称">
          <span>{{ editData.postCname }}</span>
        </FIFormItem>
      </el-col>
    </el-row>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="岗位用户列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="dataList"
      primaryKey="formId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      delete-id="deletePostUsers"
      :saveSuccessful="saveSuccessful"
      :showSaveModel="false"
      :settingConfig="settingConfig"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-delete="deleteRow"
      @on-cell-select="selectClick"
    >
      <template #headerBtn>
        <FIButton id="savePostUsers" border @click="saveBtn">保存</FIButton>
      </template>
      <!-- <template #loginName="{ scope }">
        <FISelect
          v-if="scope.row._isNew"
          v-model="scope.row.loginName"
          :options="userList"
          valueCustom="loginName"
          popperClass="select-loginName-class"
          :props="{ value: 'loginName', label: 'loginName' }"
          :display-key="['loginName', 'userName']"
          @eidt-change="handleSelect($event, scope.$index)"
          clearable
          filterable
          usePagination
          :loadMoreEnd="loadMoreEnd"
          :remote-method="remoteMethod"
          @load-more="loadMore"
        />
        <span v-if="!scope.row._isNew">{{ scope.row.loginName }}</span>
      </template> -->
      <template #partDepts="{ scope }">
        <!-- <FICascader @select-data="selectData" :showCheckbox="true" @select-node="selectNode($event,scope.$index)" id="orgId" :selectVal="scope.row.partDepts"></FICascader> -->
        <FICascaderTree
          @select-data="selectData"
          :multiple="true"
          :showCheckbox="true"
          @select-node="selectNode($event, scope.$index)"
          id="orgId"
          :selectVal="scope.row.partDepts"
          :disabled="!scope.row.isSelected"
        ></FICascaderTree>
      </template>
    </FITable>
    <template #footer>
      <slot name="footer">
        <div class="dialog-footer">
          <FIButton @click="visible = false">关闭</FIButton>
        </div>
      </slot>
    </template>
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FICascader from '@/components/FICascader.vue'
import FIModel from '@/components/FIModel.vue'
import FIAutocomplete from '@/components/FIAutocomplete.vue'
import {
  apiRegist,
  apiGetUserGroups,
  apiQueryPostUsers,
  apiSavePostUsers,
  apiDeletePostUsers,
  apiUserquery,
} from '@/api/user'
import { apiRequestPost } from '@/api/globalApi.js'
import { initSearchData } from '@/utils/common'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const emits = defineEmits(['close', 'update:setShow', 'get-list'])
const props = defineProps({
  // 圆角大小
  setShow: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const state = reactive({
  query: {
    groupEname: '',
    groupCname: '',
    current: 1,
    size: 10,
  },
})
const loadMoreEnd = ref(false)
const dataList = ref([])
const tableRef = ref(null)
const selectNode = (data, index) => {
  let arr = []
  for (let i of data) {
    arr.push(i)
  }
  tableRef.value.setCellValue(index, 'partDepts', arr)
}
//   const getPostList = () =>{
//     const par = {
// 		current:1,
// 		size:10,
//         // postCname,
//         // postEname,
// 	}
//     apiGetUserGroups(par)
//       .then((res) => {
//         if (res.data.success) {
//           dataList.value = res.data.data.result
//         } else {
//           // ElMessage.error(res.data.message)
//         }
//       })
//       .catch((error: any) => {
//         // 处理错误
//       })
//   }

const saveBtn = () => {
  let ids = []
  for (let i of checkedRows.value) {
    if (i.loginName == '') {
      useMessage().warning('请选择登录账号')
      return
    }

    let obj = {
      postId: props.editData.postId,
      userId: i.userId,
      partDepts: i.partDepts || [],
      selfdept: i.selfdept,
    }
    // if (i.selfdept) {
    //   delete obj.partDepts
    // }
    ids.push(obj)
  }
  console.log(ids, 'ids')
  if (!ids.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  const apiUrl = proxy.$Button_api('savePostUsers', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
        emits('get-list', false)
      }
    })
    .catch((error: any) => {})
}
const selectData = (val, name) => {
  // orgSelect.label = name
  // orgSelect.value = val
}

const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.userId) {
        ids.push({
          postId: item.postId,
          userId: item.userId,
        })
      }
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('deletePostUsers', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const isTableLoading = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 页面编码
const tableId = 'post_memberSet'
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  // {
  //   label: '登录账号',
  //   prop: 'loginName',
  //   align: 'center',
  //   width: '200',
  //   editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  //   editable: true,
  //   sortable: true,
  //   filterable: false,
  //   readonly: true,
  //   modelValue: { inputValue: '' },
  //   editConfig: {
  //     rules: { loginName: [{ required: true, message: '请选择登录账号', trigger: 'change' }] },
  //   },
  // },
  {
    label: '登录账号',
    prop: 'loginName',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/rm2/userMaint/query',
        props: { value: 'loginName', label: 'loginName' },
        displayKey: ['loginName', 'userName'],
        searchParam: 'userAName',
      },
    },
  },
  {
    label: '用户姓名',
    prop: 'userName',
    width: '200',
    align: 'center',
    queryName: '',
    editable: false,
    sortable: false,
    filterable: false,
    readonly: true,
  },
  {
    label: '是否所属部门任职',
    prop: 'selfdept',
    align: 'center',
    width: '200',
    queryName: '',
    filterable: false,
    editable: true,
    sortable: false,
    editType: 'select',
    editConfig: {
      options: [
        { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],
      selectBinds: {
        multiple: false,
        valueCustom: '0',
      },
    },
  },
  {
    label: '兼职部门',
    prop: 'partDepts',
    align: 'center',
    editType: 'select', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    filterable: false,
    modelValue: { inputValue: '' },
    sortable: false,
    sortValue: '',
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
let visible: any = computed({
  get() {
    return props.setShow
  },
  set(val) {
    emits('update:setShow', val)
  },
})
const addRowSave = (data) => {
  handleSave()
}
const selectClick = (scope, item) => {
  if (scope.column.property == 'loginName') {
    tableRef.value.setCellValue(scope.$index, 'userName', item.userName)
    tableRef.value.setCellValue(scope.$index, 'userId', item.userId)
  }
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  // apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
  //   .then((res) => {
  //     isTableLoading.value = false
  //     if (res.data.success) {
  //       // saveSuccessful.value = true
  //       tableRef.value.clearSelection()
  //       searchFn()
  //     } else {
  //       ElMessage.error(res.data.message)
  //     }
  //   })
  //   .catch((error: any) => {
  //     isTableLoading.value = false
  //   })
}
const searchFn = (type?: string, columnsVal?: any, orgId?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const par = {
    postId: props.editData.postId,
    ...state.query,
  }
  apiQueryPostUsers(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        dataList.value = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
        console.log(dataList.value, '重新查')
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const closeClick = () => {
  emits('update:setShow', false)
}
const saveFunc = () => {
  emits('update:setShow', false)
}
watch(
  () => props.setShow,
  (newValue) => {
    console.log(newValue, 'newValue')

    if (newValue) {
      searchFn()
    }
  },
  { immediate: true, deep: true }
)
</script>
<style lang="less" scoped></style>
